<?php

if(!defined('OI')) {
			
	print '<h1>Access Error</h1>Sorry, this file can not be accessed directly, this is strictly forbidden!';
	exit();
				
}

class Login {

	# Store digitalUniversity
	private $digitalUniversity = NULL;

	/*
	 * Constructor: Store instance of sitebuilder
	 * 	- PHP5 now uses pass by reference so we do not need to store the reference
	*/
	public function __construct(DigitalUniversity &$digitalUniversity) {
	
		$this->digitalUniversity =& $digitalUniversity;
				
	}
	
	/*
	 * Destructor: Clean memory parts
	*/
	public function __destruct() {
		
		unset($this->digitalUniversity);
		
	}
	
	/*
	 * loadPage: Detect the current page being viewed and output the relevant
	 * page contents
	*/
	public function outputPage() {
		
		# Define variables
		$noUser = false;
		$noPass = false;
		
		# Login submit
		if(isset($this->digitalUniversity->post['login'])) {
											
			# Query table	
			$userCheck = $this->digitalUniversity->db->getRow("SELECT loginKey, username, password, salt, userID FROM users WHERE username = '".$this->digitalUniversity->post['username']."'");
												
			# Did we get a record?	
			if($userCheck) {
				
				# Create password hash
				$userPass = md5($userCheck['salt'].$this->digitalUniversity->post['password']);
					
				# Do hashes match?
				if($userCheck['password'] == $userPass) {
						
					# Set cookie
					setcookie('DigitialUniversity-User', $this->digitalUniversity->encryptData($userCheck['userID'].'||'.$userCheck['loginKey']), time() + (60*60*24*365), '/');						
						
					# Redirect												
					return $this->digitalUniversity->redirect('home');
					
				} else {
						
					$noPass = true;
						
				}
				
			} else {
				
				$noUser = true;
				
			}
			
		}
				
		# Already logged in?
		if(!empty($this->digitalUniversity->user)) {
		
			return $this->digitalUniversity->redirect('home');
			
		} else {
						
			echo '<section class="login">
				<div id="universityPicture"></div>
				<img class="logo" src="'.$this->digitalUniversity->config['img_root'].'template/logo.png" alt="Digitial University" />
				<div class="dialog">
					<form action="'.$this->digitalUniversity->config['root_url'].'index.php?page=login" method="post" autocomplete="off" name="loginForm">
						<input class="textbox" name="username" type="text" placeholder="username" autofocus="autofocus"'.($noUser ? ' style="border: 1px solid red;"' : '').' />
						<input class="textbox" name="password" type="password" placeholder="PASSWORD"'.($noPass ? ' style="border: 1px solid red;"' : '').' />
						<input class="submit" name="login" type="submit" value="Log In" />
					</form>
					<a href="https://register.liv.ac.uk/ResetPassword/" target="_blank">Forgotten username or password?</a>	
				</div>
			</section>';
			
		}
										
	}
		
}

?>